package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.douwong.student.R;
import com.douwong.student.activity.FeaturesActivity;
import com.douwong.student.adapter.PrepareDetailAdapter;
import com.douwong.student.adapter.PrepareDetailResourceAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.db.PrepareReaourceDBService;
import com.douwong.student.interfaces.DetailNotify;
import com.douwong.student.interfaces.PrepareDetailResult;
import com.douwong.student.model.FeaturesBean;
import com.douwong.student.model.PrepareResource;
import com.douwong.student.model.PrepareTask;
import com.douwong.student.model.PrepareTest;
import com.douwong.student.model.PrepareTitle;
import com.douwong.student.popuwindow.UpLoadPopuWindow;
import com.douwong.student.task.PrepareDetailTask;
import com.douwong.student.task.PrepareTestDetailTask;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.JsonUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

/**
 * 备课详情 碎片
 * 
 * @author Administrator
 * 
 */
@SuppressLint("ValidFragment")
public class PrepareDetailFragment extends Fragment {

	private View view;
	private ImageView load_onekey_img;
	private ArrayList<FeaturesBean> featureList;//导读集合
	private ArrayList<PrepareTest> testList;//测试集合
	private ArrayList<PrepareTask> taskList;//考试集合
	private ArrayList<PrepareResource> resourceList = new ArrayList<PrepareResource>();//资源集合
	private ArrayList<PrepareTitle> titleList = new ArrayList<PrepareTitle>();;
	private MyGridView title_gridview, resource_gridview;
	private PrepareDetailAdapter titleAdapter;
	private PrepareDetailResourceAdapter resourceAdapter;
	private ScrollView scrollView;
	private BaseApplication app;
	private Animation animation=null;
	private UpLoadPopuWindow popu;
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(CommonConfig.PREPARE_DETAIL)) {
				popu.showAtLocation(getView(), Gravity.CENTER,0,0);
				popu.setText("加载中...");
				setData(intent);
			} else if (action.equals(CommonConfig.CHANGE_RESOURCE_STATE)) {
				int id = intent.getIntExtra("fileId", 0);
				for (int i = 0; i < resourceList.size(); i++) {
					if (id == resourceList.get(i).getId()) {
						if (intent.getStringExtra("loadState").equals("Loaded")) {
							resourceList.get(i).setLoaded(true);
							resourceList.get(i).setLoading(false);
						} else if (intent.getStringExtra("loadState").equals("Delete")) {
							resourceList.get(i).setLoaded(false);
							resourceList.get(i).setLoading(false);
						}
						resourceAdapter.notifyDataSetChanged();
						break;
					}
				}
			}
		}
	};
	IntentFilter filter = new IntentFilter() {
		{
			addAction(CommonConfig.PREPARE_DETAIL);
			addAction(CommonConfig.CHANGE_RESOURCE_STATE);
		}
	};

	private void setData(Intent intent) {

		try {
			titleList.clear();
			resourceList.clear();
			titleAdapter.notifyDataSetChanged();
			resourceAdapter.notifyDataSetChanged();
			PrepareDetailTask task = new PrepareDetailTask();
			task.setDetailResult(new PrepareDetailResult() {

				@Override
				public void detailNotify(int stateCode, List<FeaturesBean> features, List<PrepareResource> resources,
						List<PrepareTest> tests, List<PrepareTask> tasks) {
					if (stateCode == PrepareDetailTask.REQUEST_OK) {
						featureList = (ArrayList<FeaturesBean>) features;
						testList = (ArrayList<PrepareTest>) tests;
						taskList = (ArrayList<PrepareTask>) tasks;
						if (resources != null) {
							resourceList.addAll(resources);
						}
						titleList.clear();
						if (features != null) {
							for (int i = 0; i < featureList.size(); i++) {
								PrepareTitle title = new PrepareTitle();
								title.setName(featureList.get(i).getTitle());
								title.setId(featureList.get(i).getId());
								title.setType(1);
								titleList.add(title);
							}
						}
//						if (testList != null) {
//							for (int i = 0; i < testList.size(); i++) {
//								PrepareTitle title = new PrepareTitle();
//								title.setName(testList.get(i).getExTitle());
//								title.setId(testList.get(i).getId());
//								title.setType(2);
//								titleList.add(title);
//							}
//						}

						if (taskList != null) {
							for (int i = 0; i < taskList.size(); i++) {
								PrepareTitle title = new PrepareTitle();
								title.setName(taskList.get(i).getTaskTitle());
								title.setId(taskList.get(i).getId());
								title.setType(3);
								titleList.add(title);
							}
						}

					} else {
						Toast.makeText(getActivity(), "请求数据失败", Toast.LENGTH_LONG).show();
					}

					if (resourceList.size() > 0) {
						for (int i = 0; i < resourceList.size(); i++) {
							PrepareResource temp = null;
							PrepareResource prepareResource = resourceList.get(i);
							temp = PrepareReaourceDBService.getInstance(getActivity()).query(prepareResource.getId());
							if (temp != null) {// 下载列表有这一数据
								prepareResource.setLoading(temp.isLoading());
								prepareResource.setLoaded(temp.isLoaded());
								prepareResource.setFilePath(temp.getFilePath());
							} else {
							}

						}
					}
					if(popu!=null&&popu.isShowing()){
						popu.dismiss();
					}
					titleAdapter.notifyDataSetChanged();
					resourceAdapter.notifyDataSetChanged();

				}
			});
			task.execute(String.valueOf(intent.getIntExtra("prepareId", -1)));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		app = (BaseApplication) activity.getApplication();
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.prepare_detail_layout, null);
		initView();
		popu=new UpLoadPopuWindow(getActivity());
		animation=AnimationUtils.loadAnimation(getActivity(), R.anim.btn_click);
		getActivity().registerReceiver(receiver, filter);
		return view;
	}
	private void initView() {
		load_onekey_img = (ImageView) view.findViewById(R.id.load_onekey_img);
		title_gridview = (MyGridView) view.findViewById(R.id.title_gridview);
		resource_gridview = (MyGridView) view.findViewById(R.id.resource_gridview);
		scrollView = (ScrollView) view.findViewById(R.id.detail_scroll);
		scrollView.setOverScrollMode(View.OVER_SCROLL_NEVER);

		titleAdapter = new PrepareDetailAdapter(getActivity(), titleList);
		resourceAdapter = new PrepareDetailResourceAdapter(getActivity(), resourceList);
		title_gridview.setAdapter(titleAdapter);
		resource_gridview.setAdapter(resourceAdapter);
		titleGridViewOnClick();
		resourceGridviewOnClick();
		load_onekey_img.setOnClickListener(new PrepareDetailOnClick());
	}

	private class PrepareDetailOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			// 一键下载
			case R.id.load_onekey_img:
				if (resourceList.size() > 0) {
					for (int i = 0; i < resourceList.size(); i++) {
						beginLoadResource(i);
					}
					resourceAdapter.notifyDataSetChanged();
				}
				
				break;
			default:
				break;
			}
		}

	}
//点击资源列表
	private void resourceGridviewOnClick() {
		resource_gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (resourceList.get(position).isLoaded()) {
					view.startAnimation(animation);
					FileUtils.openFile(resourceList.get(position).getFilePath(),
							resourceList.get(position).getFileName(), getActivity());
				} else if (resourceList.get(position).isLoading()) {

				} else {
					beginLoadResource(position);
					resourceAdapter.notifyDataSetChanged();
				}
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	private void beginLoadResource(int i) {
		PrepareResource temp = null;
		PrepareResource prepareResource = resourceList.get(i);
		temp = PrepareReaourceDBService.getInstance(getActivity()).query(prepareResource.getId());
		if (temp != null) {// 下载列表有这一数据
			Toast.makeText(getActivity(), "已在下载列表", Toast.LENGTH_LONG).show();
		} else {
			prepareResource.setFilePath(FileUtils.RESOURCE_DIR + prepareResource.getFileName());
			prepareResource.setLoading(true);
			Intent intent = new Intent();
			intent.setAction(CommonConfig.GET_RESOURCE_LOAD);
			intent.putExtra("resource", JsonUtils.serialize(prepareResource));
			getActivity().sendBroadcast(intent);
		}
//		if (resourceList.size() > 0) {
//			for (int i = 0; i < resourceList.size(); i++) {
//				PrepareResource temp = null;
//				PrepareResource prepareResource = resourceList.get(i);
//				temp = PrepareReaourceDBService.getInstance(getActivity()).query(prepareResource.getId());
//				if (temp != null) {// 下载列表有这一数据
//					Toast.makeText(getActivity(), "已在下载列表", Toast.LENGTH_LONG).show();
//				} else {
//					prepareResource.setFilePath(FileUtils.RESOURCE_DIR + prepareResource.getFileName());
//					prepareResource.setLoading(true);
//					Intent intent = new Intent();
//					intent.setAction(CommonConfig.GET_RESOURCE_LOAD);
//					intent.putExtra("resource", JsonUtils.serialize(prepareResource));
//					getActivity().sendBroadcast(intent);
//				}
//				/*
//				 * try { Thread.sleep(500); } catch (InterruptedException e) {
//				 * e.printStackTrace(); }
//				 */
//			}
//			 resourceAdapter.notifyDataSetChanged();
//		}
	}
	private void titleGridViewOnClick() {
		title_gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (titleList.get(position).getType() == 1) {// 导读
					for (int i = 0; i < featureList.size(); i++) {
						if (titleList.get(position).getId() == featureList.get(i).getId()) {
							view.startAnimation(animation);
							Intent daoduIntent = new Intent();
							daoduIntent.putExtra("features", featureList.get(i).getIntroInfo());
							daoduIntent.setClass(getActivity(), FeaturesActivity.class);
							startActivity(daoduIntent);
							break;
						}
					}

				} else if (titleList.get(position).getType() == 2) {// 测试
					if (!NetUtils.NetwrokIsUseful(getActivity())) {
						Toast.makeText(getActivity(), "无网络连接", Toast.LENGTH_LONG).show();
						return;
					}
					for (int i = 0; i < testList.size(); i++) {
						if (titleList.get(position).getId() == testList.get(i).getId()) {
							PrepareTestDetailTask testTask = new PrepareTestDetailTask(2);
							testTask.setDetailListener(new DetailNotify() {

								@Override
								public void notify(int stateCode, String content) {
									if (stateCode == PrepareTestDetailTask.REQUEST_OK) {
									/*	Intent intent = new Intent();
										intent.setClass(getActivity(), QuizzesActivity.class);
										intent.putExtra("json", content);*/
										// startActivity(intent);
									}
								}
							});
							testTask.execute(String.valueOf(testList.get(i).getId()));
							break;
						}
					}
				}
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(receiver);
	}
}
